import { dateUtil } from '@/utils/dateUtil.js';

let token_type = 'bearer';
let acc_token_header_key = 'Authorization';

/**
 * 埋点
 * @param{String} code 埋点id
 */
const main = (code) => {
  setPoint(code);
  hits();
};

// 徐的访问量埋点
const setPoint = (code) => {
  if (!code) return Promise.reject(new Error('埋点缺失'));
  const url =
    process.env.NODE_ENV === 'development'
      ? 'https://api.wxls.pro/boya'
      : 'https://api.wxls.pro/boya';
  try {
    let header = {};
    const token = uni.getStorageSync('wxlsToken');
    header[acc_token_header_key] = `${token_type} ${token}`;

    uni.request({
      url: `${url}/api/integral/setPoint?code=${code}`,
      method: 'GET',
      header,
      success: (res) => {
        // console.log(res.data.success);
      },
    });
  } catch (e) {
    return Promise.reject(new Error('埋点缺失'));
  }
};

/**
 * 获取指定栏目下的第一篇文章作文埋点文章使用
 */
const hits = () => {
  try {
    uni.request({
      url: 'https://api.wxls.pro/news/news/api/news?count=10&page=1&type=0&catid=1898',
      method: 'GET',
      success: (res) => {
        if (res.data.data.items.length === 0) return;
        const item = res.data.data.items[0];
        getuiCode({
          id: item.source_id, // TODO 埋点ID
          name: item.title,
          createTime: dateUtil
            .unix(item.inputtime)
            .format('YYYY-MM-DD HH:mm:ss'),
        });
        memberPoints(item);
      },
    });
  } catch (e) {}
};

/**
 * 埋点方法(省里的埋点)
 * @param {*} item
 */
const getuiCode = (item) => {
  try {
    GetuiDataSDK.track('newsInfoPv', {
      NewsArticleID: item.id,
      NewsArticleTitle: item.name,
      SelfNewsArticleID: item.id,
      NewsArticlePubtime: item.createTime,
    });
  } catch (e) {
    //TODO handle the exception
  }
};

/**
 * 威宗的埋点
 */
const memberPoints = (item) => {
  let selfData = {
    deviceNumber: '',
    articleId: item.source_id.toString(),
    articleTitle: item.title,
    pointsType: 'read',
    type: 0,
    catId: item.category.catid,
    catName: item.category.catname,
  };
  try {
    uni.request({
      url: 'https://integral.wxls.pro/apiPass/memberPoints',
      data: selfData,
      method: 'POST',
      success: (res) => {},
    });
  } catch (e) {}
};

export { main, setPoint };
